package com.generator.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.generator.entity.DatasourceConfig;
import com.generator.gen.DbType;
import com.generator.mapper.DatasourceConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author tanghc
 */
@Service
public class DatasourceConfigService {

    @Autowired
    private DatasourceConfigMapper datasourceConfigMapper;

    public DatasourceConfig getById(int id) {
        return datasourceConfigMapper.getById(id);
    }

    public List<DatasourceConfig> listAll() {
        return datasourceConfigMapper.listAll();
    }
    public ResponseEntity list(Page pageDto, DatasourceConfig datasourceConfig) {
        IPage iPage = datasourceConfigMapper.selectPage(pageDto, new LambdaQueryWrapper(datasourceConfig));
        pageDto.setRecords(iPage.getRecords());
        pageDto.setTotal(iPage.getTotal());
        return ResponseEntity.ok(pageDto);
    }

    public ResponseEntity save(DatasourceConfig templateConfig){
        if(ObjectUtils.isEmpty(templateConfig.getId())){
            insert(templateConfig);
        }else{
            update(templateConfig);
        }
        return ResponseEntity.ok().build();
    }

    public ResponseEntity del(List<Integer> ids){
        datasourceConfigMapper.deleteBatchIds(ids);
        return ResponseEntity.ok().build();
    }



    public void insert(DatasourceConfig templateConfig) {
        templateConfig.setIsDeleted(0);
        DbType dbType = DbType.of(templateConfig.getDbType());
        if (dbType != null) {
            templateConfig.setDriverClass(dbType.getDriverClass());
        }
        datasourceConfigMapper.insert(templateConfig);
    }

    public void update(DatasourceConfig templateConfig) {
        datasourceConfigMapper.update(templateConfig);
    }

    public void delete(DatasourceConfig templateConfig) {
        datasourceConfigMapper.delete(templateConfig);
    }
}
